package com.py.credit.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.Dept;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.ResourceTableFieldsEnum;
import com.py.credit.service.DeptService;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.service.TableService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

@RestController
@RequestMapping(value = "/table")
public class TableController {

	private final static String FRONT_TABLE_ID = "sharing";

	@Autowired
	TableService tableService;

	@Autowired
	private RemoteBaseService remoteBaseService;

	@Autowired
	private DeptService deptService;

	/**
	 * 删除常用信息资源
	 */
	@RequestMapping(value = "/delSharingResouce.json")
	public RestServiceResult<Object> delSharingResouce(
			@RequestParam(value = "ids", defaultValue = "", required = true) String ids) {

		tableService.del(ids, "S", null, null);

		return new RestServiceResult<Object>();

	}

	/**
	 * 常用信息资源列表
	 */

	@RequestMapping(value = "/getTableList.json")
	public RestServiceResult<List<Map<String, Object>>> getTableList(
			@RequestParam(value = "kId", defaultValue = "", required = true) String kId,
			@RequestParam(value = "type", defaultValue = "", required = true) String type,
			@RequestParam(value = "deptId", defaultValue = "", required = true) String deptId,
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
			HttpServletRequest request) {

		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

		String[] configColumns = null;

		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

			SysUser userInfo = user.getData();

			if (null != userInfo) {

				configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_ID);

			} else {

				ExceptionLogger.error("TableController#getTableList", "未获取到当前用户信息！");
			}

		} else {

			ExceptionLogger.error("TableController#getTableList", "未获取到当前用户信息！");
		}

		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? ResourceTableFieldsEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);

		String[] additionalColumns = { "tableId", "deptId", "kId" };

		List<Map<String, Object>> tableList = tableService.getSharingResouceByConditionForPage(kId, deptId, showColumns,
				additionalColumns, condition, page);

		return new RestServiceResult<List<Map<String, Object>>>(page.getTotalCount(), tableList);

	}

	@RequestMapping(value = "/addShowColunms.json")
	public RestServiceResult<String> addShowColunms(@RequestParam(value = "columns", required = true) String[] columns,
			HttpServletRequest request) {

		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

			SysUser userInfo = user.getData();

			if (null != userInfo) {

				MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_ID, columns);

			} else {

				ExceptionLogger.error("TableController#addShowColunms", "未获取到当前用户信息！");
			}

		} else {

			ExceptionLogger.error("TableController#addShowColunms", "未获取到当前用户信息！");
		}

		return new RestServiceResult<String>();
	}

	@RequestMapping(value = "/export.json")
	public void export(@RequestParam(value = "kId", defaultValue = "", required = true) String kId,
			@RequestParam(value = "deptId", defaultValue = "", required = true) String deptId,
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition,
			@RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN, Page page,
			HttpServletResponse response) throws IOException {

		page.setLimit(1000);

		List<String> columns = JSONArray.parseArray(columnEN, String.class);

		List<Map<String, Object>> data = tableService.getSharingResouceByConditionForPage(kId, deptId, columns, null,
				condition, page);

		List<OptionalColumn> optionalColumns = ResourceTableFieldsEnum.getOptionalColumns();

		ExcelUtil.downloadExcel(response, data, "常用信息资源", "常用信息资源", columns, optionalColumns);

	}

	/**
	 * 分配常用信息资源
	 *
	 * @return
	 */

	@RequestMapping(value = "/distributeCommonResource.json")
	public RestServiceResult<String> distributeCommonResource(
			@RequestParam(value = "dept", defaultValue = "", required = true) String dept,
			@RequestParam(value = "tableId", defaultValue = "", required = true) int tableId,
			@RequestParam(value = "kId", defaultValue = "", required = true) String kId) {

		List<Map<String, String>> depts = JSON.parseObject(dept, new TypeReference<List<Map<String, String>>>() {
		});

		tableService.distributeCommonResource(kId, tableId, depts);

		return new RestServiceResult<String>();

	}

	/**
	 * 分配部门信息
	 *
	 * @return
	 */

	@RequestMapping(value = "/distributeDept.json")
	public RestServiceResult<List<Dept>> distributeDept(
			@RequestParam(value = "tableId", defaultValue = "", required = true) int tableId,
			@RequestParam(value = "kId", defaultValue = "", required = true) String kId) {

		List<Dept> rootOffices = deptService.getTopLevelDept();

		if (!CollectionUtils.isEmpty(rootOffices)) {

			List<Dept> alreadyDistributeRecord = tableService.getAlreadyDistributeRecord(tableId, kId);

			for (Dept office : rootOffices) {

				for (Dept dept : alreadyDistributeRecord) {

					if (dept.getId() != null && office.getId().longValue() == dept.getId().longValue()) {

						office.setChecked(true);

						office.setDeptSort(dept.getDeptSort() != null ? dept.getDeptSort() : 0);

						break;

					}

				}

			}

		}

		return new RestServiceResult<List<Dept>>(rootOffices);

	}

	@RequestMapping(value = "/detail")
	public RestServiceResult<Map<String, Object>> detail(
			@RequestParam(value = "tableId", defaultValue = "", required = true) int tableId,
			@RequestParam(value = "kId", defaultValue = "", required = true) String kId,
			@RequestParam(value = "deptId", defaultValue = "", required = true) String deptId) {
		Map<String, Object> tableInfo = tableService.getSharingTableInfo(kId, deptId, tableId);
		return new RestServiceResult<Map<String, Object>>(tableInfo);
	}

}
